import path from 'path';
import * as vscode from 'vscode';
import { exec_cmd, getConfiguration, logToChannel } from '../utils';



function build(filePath: string, extensionPath: string) {
  const { output_path, id_pre, id_type } = getConfiguration();
  const buildScriptPath = path.join(extensionPath, 'src', 'lib', 'sfc-builder-cli.min.cjs');
  logToChannel(`开始编译 ${filePath}`);
  const detail = `
  sfcPath ==> ${filePath}
  outputPath ==> ${output_path}`;
  exec_cmd(
    `node ${buildScriptPath} build -t ${id_type}  --outputPath ${output_path} --idPre ${id_pre} ${filePath}`,
    { title: `编译完成`, detail },
    { title: `编译失败!`, detail },
  )
}
let fileWatcher: vscode.Disposable | null = null;
let changeWatcher: vscode.Disposable | null = null;
let hasChanges = false
export function setupBuildCommand(context: vscode.ExtensionContext) {



  // 如果已经存在监听器
  if (fileWatcher && changeWatcher) {
    vscode.window.showInformationMessage('sfc-builder: 文件监听已启动,保存Vue文件时将自动构建');
    return;
  }
  const extensionPath = context.extensionPath;
  // 创建内容变化监听器
  changeWatcher = vscode.workspace.onDidChangeTextDocument(event => {
    if (event.document.languageId === 'vue' && event.document.isDirty) {
      hasChanges = true;
    }
  });

  // 创建文件监听器
  fileWatcher = vscode.workspace.onDidSaveTextDocument(doc => {
    if (doc.languageId === 'vue' && hasChanges) {
      build(doc.fileName, extensionPath);
      hasChanges = false;
    }
  });

  context.subscriptions.push(fileWatcher, changeWatcher);
  logToChannel('开始监听Vue文件保存事件');
  vscode.window.showInformationMessage('sfc-builder: 开始监听Vue文件保存事件,保存Vue文件时将自动构建');

}